<?php

namespace Core\Http;

use Core\Support\Json;
use Core\Support\SingleTon;
use Illuminate\Support\Arr;
use Symfony\Component\HttpFoundation\Request as HttpFoundationRequest;

class Request extends HttpFoundationRequest
{
    use SingleTon;
    use RequestValidation;

    protected $jsonData;

    /**
     * 获取数据类型是json的数据
     */
    public function getJson(string $key = null, mixed $default = null): mixed
    {
        if (is_null($this->jsonData)) {
            $data = $this->getContent();
            if (!empty($data) && $this->getContentType() == 'json') {
                $this->jsonData = Json::decode($data, true);
            }
        }

        return $key ? Arr::get($this->jsonData, $key, $default) : $this->jsonData;
    }

    /**
     * 获取请求ID, 接收来之 X-Request-Id 的数据
     */
    public function getRequestId()
    {
        $requestId = $this->headers->get('X-Request-Id');
        return strtoupper($requestId);
    }

    /**
     * Returns the user.
     */
    public function getUser(): ?string
    {
        return $this->headers->get('AUTH_USER');
    }

    /**
     * Returns the password.
     */
    public function getPassword(): ?string
    {
        return $this->headers->get('AUTH_PW');
    }

    /**
     * get header
     */
    public function header($name)
    {
        return $this->headers->get($name);
    }

    // get user agent
    public function userAgent()
    {
        return $this->headers->get('User-Agent');
    }
}
